package com.john.ishadowsocks.auto.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.Charset;

/**
 * <<文件操作工具类>>
 *
 * @author John
 * @date 2016/5/21
 * @email jiangguangtao@foxmail.com
 */
public class FileUtil {
    private static final Logger log = LoggerFactory.getLogger(FileUtil.class);
    public static final Charset UTF_8 = Charset.forName("UTF-8");

    /**
     * 以UTF-8方式读取流到字符串中
     *
     * @param inputStream
     * @return
     */
    public static String read2String(InputStream inputStream) {
        return read2String(inputStream, UTF_8);
    }


    /**
     * 读取输入流到文本文件中
     *
     * @param inputStream
     * @param charset
     * @return
     */
    public static String read2String(InputStream inputStream, Charset charset) {
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();
        String str;
        try {
            br = new BufferedReader(new InputStreamReader(inputStream, charset));
            while ((str = br.readLine()) != null) {
                sb.append(str).append("\r\n");
            }
        } catch (IOException e) {
            log.error("读取文件流异常", e);
        }

        return sb.toString();
    }

    /**
     * 写文本到输出流中
     * @param outputStream
     * @param content
     */
    public static void writeString(OutputStream outputStream, String content) {
        try {
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream, UTF_8));
            bw.write(content);
            bw.flush();
        } catch (IOException e) {
            log.error("输出文件流异常", e);
        }
    }
}
